package javaTest05.utils;

import java.io.*;

public class FileUtils {
    public static byte[] getByteArrayFromFile(String path,boolean single) {//将文件转换为字节数组发送至服务端
        FileInputStream in = null;
        ByteArrayOutputStream out = null;
        byte[] res = null;

        try {
            in = new FileInputStream(path);
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];//文件读取缓存空间

            int count;
            while ((count = in.read(buffer)) != -1) {
                out.write(buffer, 0, count);
                if (single) break;//如果只读一次
            }

            res = out.toByteArray();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null){
                    in.close();
                }
                if (out != null){
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    public static void writeFileByByteArr(byte[] fileData,String path){
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path);
            out.write(fileData);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (out !=null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
